import { Router } from 'express';
import crypto from 'crypto';
import { Op } from 'sequelize';
import { db, models } from '../db';

const router = Router();
const {
  config_vip: ConfigVipModel,
  account: AccountModel,
  user: UserModel,
  user_hero: UserHeroModel,
  user_equip: UserEquipModel,
  user_log_assets: UserLogAssetsModel,
  user_log_gold: UserLogGoldModel,
} = models;

router.post(
  '/account/register',
  async (
    req: { body: { code: string; account: string; password: string; confirmPassword: string } },
    res: { send: (arg: string) => void; json: (arg: any) => void },
  ) => {
    try {
      const { code, account, password, confirmPassword } = req.body;

      if (!code || code !== '5162300') {
        return res.json({ code: 0, msg: '参数错误', data: {} });
      }

      if (password !== confirmPassword) {
        return res.json({ code: 0, msg: '两次输入密码不相同', data: {} });
      }

      const existingAccount = await AccountModel.findOne({ where: { account } });
      if (existingAccount) {
        return res.json({ code: 0, msg: '账号已存在', data: {} });
      }

      let md5 = crypto.createHash('md5');
      let newPassword = md5.update(password + 'xxsg').digest('hex');

      await AccountModel.create({ account, password: newPassword });

      return res.json({ code: 0, msg: '注册成功', data: { account: account } });
    } catch (error) {
      console.log(error);
      return res.json({ code: 0, msg: error, data: {} });
    }
  },
);

router.post('/account/active', async (req: any, res: any) => {
  const transaction = await db.transaction();

  try {
    const { account, code } = req.body;

    if (!code || code !== '5162300') {
      return res.json({ code: 0, msg: '参数错误', data: {} });
    }

    const accountInfo = await AccountModel.findOne({ where: { account } });
    if (!accountInfo) {
      return res.json({ code: 0, msg: '账号不存在', data: {} });
    }
    // 激活角色
    const { id: accountId, is_actived } = accountInfo.dataValues;

    if (is_actived) {
      return res.json({ code: 0, msg: '账号已激活, 请勿重复激活', data: {} });
    }

    const userInfo = await UserModel.create(
      {
        account_id: accountId,
        name: account,
      },
      { transaction },
    );

    // 给用户发放赵云，并上阵
    const { id: userId } = userInfo.dataValues;

    const userHero = await UserHeroModel.create(
      {
        user_id: userId,
        hero_id: 9,
        position_x: 2,
        position_y: 1,
      },
      {
        transaction,
      },
    );
    const { id: userHeroAssetId } = userHero.dataValues;

    await UserLogAssetsModel.create(
      {
        user_id: userId,
        assets_id: userHeroAssetId,
        assets_type: 'hero',
        type: 'get',
        count: 1,
        reason_type: 'vip0',
        reason: '初始化领取vip0奖励',
      },
      { transaction },
    );
    // 给用户发放龙胆亮银枪
    const userEquip = await UserEquipModel.create(
      {
        user_id: userId,
        equip_id: 20009,
      },
      { transaction },
    );
    const { id: userEquipAssetId } = userEquip.dataValues;
    await UserLogAssetsModel.create(
      {
        user_id: userId,
        assets_id: userEquipAssetId,
        assets_type: 'equip',
        type: 'get',
        count: 1,
        reason_type: 'vip0',
        reason: '初始化领取vip0奖励',
      },
      { transaction },
    );
    await transaction.commit();
    await AccountModel.update({ is_actived: 1 }, { where: { account } });

    return res.json({ code: 0, msg: '激活成功', data: {} });
  } catch (error) {
    await transaction.rollback();
    return res.json({ code: 0, msg: '服务器异常', data: {} });
  }
});

router.post('/account/recharge', async (req: any, res: any) => {
  const transaction = await db.transaction();
  try {
    const { account, count, code } = req.body;

    if (!code || code !== '5162300') {
      return res.json({ code: 0, msg: '参数错误', data: {} });
    }

    const accountInfo = await AccountModel.findOne({ where: { account } });
    if (!accountInfo) {
      return res.json({ code: 0, msg: '账号不存在', data: {} });
    }

    if (accountInfo.dataValues.is_actived === 0) {
      return res.json({ code: 0, msg: '账号未激活', data: {} });
    }

    const { id: accountId } = accountInfo.dataValues;
    const userInfo = await UserModel.findOne({ where: { account_id: accountId } });
    if (!userInfo) {
      return res.json({ code: 0, msg: '账号未创建角色', data: {} });
    }

    const { id: userId, gold, sponsor } = userInfo.dataValues;

    await UserLogGoldModel.create(
      {
        user_id: userId,
        type: 'get',
        count: count,
        reason_type: 'recharge',
        reason: '充值',
      },
      { transaction },
    );

    const totalSponsor = sponsor + count;

    const vip = await ConfigVipModel.findOne({
      where: {
        sponsor: {
          [Op.lte]: totalSponsor,
        },
      },
      order: [['sponsor', 'DESC']],
    });

    const vipLevel = vip ? vip.dataValues.id : 0;

    await UserModel.update(
      { gold: gold + count, vip: vipLevel, sponsor: totalSponsor },
      { where: { id: userId }, transaction },
    );

    await transaction.commit();
    return res.json({ code: 1, msg: '充值成功', data: {} });
  } catch (error) {
    await transaction.rollback();
    return res.json({ code: 0, msg: '服务器异常', data: {} });
  }
});

export default router;
